<template>
  <div class="page-container">
    <div class="page-header">
      <h2>用户健身数据管理</h2>
      <p>管理系统用户的健身相关数据</p>
    </div>
    
    <!-- 用户选择器 -->
    <el-card class="user-selector-card">
      <template #header>
        <div class="card-header">
          <span>选择用户</span>
        </div>
      </template>
      <el-select 
        v-model="selectedUserId" 
        placeholder="请选择用户"
        style="width: 100%;"
        @change="handleUserChange"
      >
        <el-option
          v-for="user in users"
          :key="user.id"
          :label="`${user.username} (${user.fullName || ''})`"
          :value="user.id"
        />
      </el-select>
    </el-card>
    
    <!-- 标签页 -->
    <el-tabs v-if="selectedUserId" v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="运动记录" name="exerciseRecords">
        <!-- 用户健身数据统计 -->
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>健身统计</span>
            </div>
          </template>
          <div v-loading="statsLoading" class="stats-container">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.totalDuration || 0 }}</div>
                  <div class="stat-label">累计运动时间 (分钟)</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ (stats.totalCalories || 0).toFixed(2) }}</div>
                  <div class="stat-label">累计消耗热量 (卡路里)</div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
        
        <!-- 运动记录表格 -->
        <el-card class="records-card">
          <template #header>
            <div class="card-header">
              <span>运动记录列表</span>
              <div class="header-actions">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateRangeChange"
                />
                <el-button type="primary" size="small" @click="clearDateRange">清除筛选</el-button>
              </div>
            </div>
          </template>
          
          <div v-loading="recordsLoading">
            <el-table 
              :data="records" 
              style="width: 100%" 
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="运动类型" min-width="120">
                <template #default="scope">
                  {{ scope.row.exerciseType?.name || '未知类型' }}
                </template>
              </el-table-column>
              <el-table-column label="开始时间" min-width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.startTime) }}
                </template>
              </el-table-column>
              <el-table-column label="结束时间" min-width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="durationMinutes" label="时长(分钟)" width="120" />
              <el-table-column prop="caloriesBurned" label="热量(卡路里)" width="120" />
              <el-table-column label="强度" width="100">
                <template #default="scope">
                  <el-tag :type="getIntensityType(scope.row.intensity)">
                    {{ getIntensityLabel(scope.row.intensity) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small"
                    circle
                    @click="handleEdit(scope.row)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    circle
                    @click="handleDelete(scope.row)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-empty v-if="records.length === 0" description="暂无运动记录" />
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="健康数据" name="healthData">
        <!-- 健康数据管理的内容将在这里添加 -->
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>健康数据列表</span>
            </div>
          </template>
          
          <div v-loading="healthDataLoading">
            <el-table 
              :data="healthData" 
              style="width: 100%" 
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column label="记录日期" min-width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.recordDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="height" label="身高(cm)" width="100" />
              <el-table-column prop="weight" label="体重(kg)" width="100" />
              <el-table-column prop="bmi" label="BMI" width="100" />
              <el-table-column label="BMI评估" width="120">
                <template #default="scope">
                  <el-tag :type="getBmiTagType(scope.row.bmi)">
                    {{ getBmiCategory(scope.row.bmi) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="restingHeartRate" label="静息心率(bpm)" width="140" />
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small"
                    circle
                    @click="handleEditHealthData(scope.row)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    circle
                    @click="handleDeleteHealthData(scope.row)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-empty v-if="healthData.length === 0" description="暂无健康数据" />
          </div>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="健身目标" name="fitnessGoals">
        <!-- 健身目标管理的内容将在这里添加 -->
        <el-card class="filters-card">
          <template #header>
            <div class="card-header">
              <span>目标状态筛选</span>
            </div>
          </template>
          <el-radio-group v-model="goalStatusFilter" @change="handleGoalStatusChange">
            <el-radio-button label="ALL">全部</el-radio-button>
            <el-radio-button label="ACTIVE">进行中</el-radio-button>
            <el-radio-button label="COMPLETED">已完成</el-radio-button>
            <el-radio-button label="FAILED">未达成</el-radio-button>
            <el-radio-button label="ABANDONED">已放弃</el-radio-button>
          </el-radio-group>
        </el-card>
        
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>健身目标列表</span>
            </div>
          </template>
          
          <div v-loading="goalsLoading">
            <el-table 
              :data="fitnessGoals" 
              style="width: 100%" 
              border
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="title" label="目标标题" min-width="180" />
              <el-table-column label="类型" width="120">
                <template #default="scope">
                  {{ getGoalTypeDisplayName(scope.row.type) }}
                </template>
              </el-table-column>
              <el-table-column label="目标值" width="150">
                <template #default="scope">
                  {{ scope.row.targetValue }} {{ scope.row.unit || '' }}
                </template>
              </el-table-column>
              <el-table-column label="开始日期" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.startDate) }}
                </template>
              </el-table-column>
              <el-table-column label="目标日期" width="180">
                <template #default="scope">
                  {{ formatDate(scope.row.targetDate) }}
                </template>
              </el-table-column>
              <el-table-column label="进度" width="200">
                <template #default="scope">
                  <el-progress 
                    :percentage="scope.row.progress || 0" 
                    :status="getProgressStatus(scope.row.progress)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="状态" width="120">
                <template #default="scope">
                  <el-tag :type="getGoalStatusType(scope.row.status)">
                    {{ getGoalStatusDisplayName(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="240" fixed="right">
                <template #default="scope">
                  <el-button 
                    type="primary" 
                    size="small"
                    circle
                    @click="handleEditGoal(scope.row)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button 
                    type="success" 
                    size="small"
                    circle
                    @click="handleEditGoalProgress(scope.row)"
                    :disabled="scope.row.status !== 'ACTIVE'"
                  >
                    <el-icon><Promotion /></el-icon>
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    circle
                    @click="handleDeleteGoal(scope.row)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-empty v-if="fitnessGoals.length === 0" description="暂无健身目标" />
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 编辑运动记录对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="编辑运动记录" 
      width="600px"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="运动类型" prop="exerciseTypeId">
          <el-select v-model="form.exerciseTypeId" placeholder="选择运动类型" style="width: 100%;">
            <el-option
              v-for="type in exerciseTypes"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="时长(分钟)" prop="durationMinutes">
          <el-input-number v-model="form.durationMinutes" :min="1" disabled />
          <span class="form-tip">（不可修改）</span>
        </el-form-item>
        
        <el-form-item label="热量(卡路里)" prop="caloriesBurned">
          <el-input-number v-model="form.caloriesBurned" :min="0" :precision="2" :step="0.01" disabled />
          <span class="form-tip">（不可修改）</span>
        </el-form-item>
        
        <el-form-item label="强度" prop="intensity">
          <el-select v-model="form.intensity" placeholder="选择强度" style="width: 100%;">
            <el-option label="低强度" value="LOW" />
            <el-option label="中等强度" value="MEDIUM" />
            <el-option label="高强度" value="HIGH" />
            <el-option label="极高强度" value="VERY_HIGH" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="地点" prop="location">
          <el-input v-model="form.location" placeholder="输入运动地点" />
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            placeholder="输入备注"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑健康数据对话框 -->
    <el-dialog
      v-model="healthDataDialogVisible"
      title="编辑健康数据"
      width="600px"
    >
      <el-form
        ref="healthDataFormRef"
        :model="healthDataForm"
        :rules="healthDataRules"
        label-width="100px"
      >
        <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="healthDataForm.recordDate"
            type="datetime"
            placeholder="选择记录日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="身高(cm)" prop="height">
          <el-input-number v-model="healthDataForm.height" :min="50" :max="250" :step="0.1" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="体重(kg)" prop="weight">
          <el-input-number v-model="healthDataForm.weight" :min="20" :max="300" :step="0.1" style="width: 100%;" />
        </el-form-item>
        
        <el-form-item label="BMI" prop="bmi">
          <el-input-number v-model="healthDataForm.bmi" disabled style="width: 100%;" />
          <span v-if="healthDataForm.bmi" class="form-tip">
            ({{ getBmiCategory(healthDataForm.bmi) }})
          </span>
        </el-form-item>
        
        <el-form-item label="静息心率" prop="restingHeartRate">
          <el-input-number v-model="healthDataForm.restingHeartRate" :min="30" :max="200" style="width: 100%;" />
          <span class="form-tip">次/分钟</span>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="healthDataDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHealthDataForm" :loading="healthDataSubmitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑健身目标对话框 -->
    <el-dialog
      v-model="goalDialogVisible"
      title="编辑健身目标"
      width="600px"
    >
      <el-form
        ref="goalFormRef"
        :model="goalForm"
        :rules="goalRules"
        label-width="100px"
      >
        <el-form-item label="目标标题" prop="title">
          <el-input v-model="goalForm.title" placeholder="输入目标标题" />
        </el-form-item>
        
        <el-form-item label="目标类型" prop="type">
          <el-select v-model="goalForm.type" placeholder="选择目标类型" style="width: 100%;">
            <el-option label="减重目标" value="WEIGHT_LOSS" />
            <el-option label="运动频率" value="EXERCISE_FREQUENCY" />
            <el-option label="距离目标" value="DISTANCE" />
            <el-option label="力量目标" value="STRENGTH" />
            <el-option label="耐力目标" value="ENDURANCE" />
            <el-option label="自定义" value="CUSTOM" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标描述" prop="description">
          <el-input
            v-model="goalForm.description"
            type="textarea"
            :rows="3"
            placeholder="输入目标描述"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目标值" prop="targetValue">
              <el-input v-model="goalForm.targetValue" placeholder="输入目标数值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="goalForm.unit" placeholder="输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="goalForm.startDate"
            type="datetime"
            placeholder="选择开始日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="目标日期" prop="targetDate">
          <el-date-picker
            v-model="goalForm.targetDate"
            type="datetime"
            placeholder="选择目标日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="目标进度" prop="progress">
          <el-slider
            v-model="goalForm.progress"
            :min="0"
            :max="100"
            :format-tooltip="value => `${value}%`"
            :step="1"
            show-input
          />
        </el-form-item>
        
        <el-form-item label="目标状态" prop="status">
          <el-select v-model="goalForm.status" placeholder="选择状态" style="width: 100%;">
            <el-option label="进行中" value="ACTIVE" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="未达成" value="FAILED" />
            <el-option label="已放弃" value="ABANDONED" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="goalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGoalForm" :loading="goalSubmitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑目标进度对话框 -->
    <el-dialog
      v-model="progressDialogVisible"
      title="更新目标进度"
      width="500px"
    >
      <div v-if="currentGoal" class="progress-form">
        <h3>{{ currentGoal.title }}</h3>
        <p v-if="currentGoal.description">{{ currentGoal.description }}</p>
        
        <div class="current-progress">
          <span>当前进度: {{ currentGoal.progress || 0 }}%</span>
          <el-progress
            :percentage="currentGoal.progress || 0"
            :status="getProgressStatus(currentGoal.progress)"
          />
        </div>
        
        <el-form>
          <el-form-item label="更新进度" label-width="80px">
            <el-slider
              v-model="progressValue"
              :min="0"
              :max="100"
              :format-tooltip="value => `${value}%`"
              :step="1"
              show-input
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="progressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateGoalProgress" :loading="progressSubmitting">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete, Promotion } from '@element-plus/icons-vue'
import { getUserList } from '@/api/user'
import { getAllExerciseTypes } from '@/api/exerciseType'
import {
  getUserExerciseRecords,
  getUserExerciseStats,
  getUserExerciseRecordsByDateRange,
  updateUserExerciseRecord,
  deleteUserExerciseRecord,
  getUserHealthData,
  getUserHealthDataById,
  updateUserHealthData,
  deleteUserHealthData,
  getUserFitnessGoals,
  getUserFitnessGoalsByStatus,
  getUserFitnessGoalById,
  updateUserFitnessGoal,
  updateUserGoalProgress,
  deleteUserFitnessGoal
} from '@/api/admin'

// 当前活动的标签页
const activeTab = ref('exerciseRecords')

// 数据加载状态
const users = ref([])
const selectedUserId = ref(null)
const records = ref([])
const stats = ref({
  totalDuration: 0,
  totalCalories: 0
})
const exerciseTypes = ref([])
const recordsLoading = ref(false)
const statsLoading = ref(false)
const dateRange = ref(null)

// 健康数据相关
const healthData = ref([])
const healthDataLoading = ref(false)
const healthDataDialogVisible = ref(false)
const healthDataSubmitting = ref(false)
const healthDataFormRef = ref(null)
const currentHealthData = ref(null)

const healthDataForm = ref({
  recordDate: null,
  height: 170,
  weight: 65,
  bmi: null,
  restingHeartRate: 70
})

const healthDataRules = {
  recordDate: [{ required: true, message: '请选择记录日期', trigger: 'change' }],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' },
    { type: 'number', min: 50, max: 250, message: '身高必须在50-250cm之间', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' },
    { type: 'number', min: 20, max: 300, message: '体重必须在20-300kg之间', trigger: 'blur' }
  ]
}

// 健身目标相关
const fitnessGoals = ref([])
const goalsLoading = ref(false)
const goalStatusFilter = ref('ALL')
const goalDialogVisible = ref(false)
const goalSubmitting = ref(false)
const goalFormRef = ref(null)
const currentGoal = ref(null)

const goalForm = ref({
  title: '',
  description: '',
  type: '',
  targetValue: '',
  unit: '',
  startDate: null,
  targetDate: null,
  progress: 0,
  status: 'ACTIVE'
})

const goalRules = {
  title: [
    { required: true, message: '请输入目标标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符之间', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }]
}

// 进度更新对话框
const progressDialogVisible = ref(false)
const progressSubmitting = ref(false)
const progressValue = ref(0)

// 编辑表单相关
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const currentRecord = ref(null)

const form = ref({
  exerciseTypeId: null,
  startTime: null,
  endTime: null,
  durationMinutes: 0,
  caloriesBurned: 0,
  intensity: 'MEDIUM',
  location: '',
  notes: ''
})

const rules = {
  exerciseTypeId: [{ required: true, message: '请选择运动类型', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  durationMinutes: [{ required: true, message: '请输入运动时长', trigger: 'blur' }]
}

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取强度标签
const getIntensityLabel = (intensity) => {
  const map = {
    LOW: '低强度',
    MEDIUM: '中等强度',
    HIGH: '高强度',
    VERY_HIGH: '极高强度'
  }
  return map[intensity] || '中等强度'
}

// 获取强度标签类型
const getIntensityType = (intensity) => {
  const map = {
    LOW: 'success',
    MEDIUM: 'info',
    HIGH: 'warning',
    VERY_HIGH: 'danger'
  }
  return map[intensity] || 'info'
}

// 获取强度系数
const getIntensityMultiplier = (intensity) => {
  const multiplierMap = {
    'LOW': 0.8,
    'MEDIUM': 1.0,
    'HIGH': 1.2,
    'VERY_HIGH': 1.5
  }
  return multiplierMap[intensity] || 1.0
}

// 获取所有用户
const fetchUsers = async () => {
  try {
    users.value = await getUserList()
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取所有运动类型
const fetchExerciseTypes = async () => {
  try {
    exerciseTypes.value = await getAllExerciseTypes()
  } catch (error) {
    console.error('获取运动类型失败:', error)
    ElMessage.error('获取运动类型失败')
  }
}

// 获取用户统计数据
const fetchUserStats = async (userId) => {
  if (!userId) return
  
  statsLoading.value = true
  try {
    stats.value = await getUserExerciseStats(userId)
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
    ElMessage.error('获取用户统计数据失败')
  } finally {
    statsLoading.value = false
  }
}

// 获取用户运动记录
const fetchUserRecords = async (userId) => {
  if (!userId) return
  
  recordsLoading.value = true
  try {
    records.value = await getUserExerciseRecords(userId)
  } catch (error) {
    console.error('获取用户运动记录失败:', error)
    ElMessage.error('获取用户运动记录失败')
  } finally {
    recordsLoading.value = false
  }
}
function formatDate1(date) {
  if (!date) return ''
  const d = new Date(date)
  const pad = n => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

// 按日期范围筛选记录
const fetchUserRecordsByDateRange = async (userId, startDate, endDate) => {
  if (!userId || !startDate || !endDate) return

  // 这里加上格式化
  const formattedStart = formatDate1(startDate)
  const formattedEnd = formatDate1(endDate)

  recordsLoading.value = true
  try {
    records.value = await getUserExerciseRecordsByDateRange(userId, formattedStart, formattedEnd)
  } catch (error) {
    console.error('按日期范围获取用户运动记录失败:', error)
    ElMessage.error('按日期范围获取用户运动记录失败')
  } finally {
    recordsLoading.value = false
  }
}

// 处理用户切换
const handleUserChange = (userId) => {
  if (!userId) return
  
  dateRange.value = null // 清除日期范围筛选
  
  // 根据当前活动的标签页加载对应数据
  if (activeTab.value === 'exerciseRecords') {
    fetchUserStats(userId)
    fetchUserRecords(userId)
  } else if (activeTab.value === 'healthData') {
    fetchUserHealthData(userId)
  } else if (activeTab.value === 'fitnessGoals') {
    fetchUserFitnessGoals(userId)
  }
}

// 处理标签页切换
const handleTabClick = (tab) => {
  if (!selectedUserId.value) return
  
  if (tab.props.name === 'exerciseRecords') {
    fetchUserStats(selectedUserId.value)
    fetchUserRecords(selectedUserId.value)
  } else if (tab.props.name === 'healthData') {
    fetchUserHealthData(selectedUserId.value)
  } else if (tab.props.name === 'fitnessGoals') {
    fetchUserFitnessGoals(selectedUserId.value)
  }
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (!dateRange.value || !selectedUserId.value) return
  
  const [startDate, endDate] = dateRange.value
  if (startDate && endDate) {
    // 设置时间为当天的开始和结束
    const start = new Date(startDate)
    start.setHours(0, 0, 0, 0)
    
    const end = new Date(endDate)
    end.setHours(23, 59, 59, 999)
    
    fetchUserRecordsByDateRange(selectedUserId.value, start, end)
  }
}

// 清除日期范围筛选
const clearDateRange = () => {
  dateRange.value = null
  if (selectedUserId.value) {
    fetchUserRecords(selectedUserId.value)
  }
}

// 当开始时间或结束时间变化时，自动计算时长
watch([() => form.value.startTime, () => form.value.endTime], ([newStartTime, newEndTime]) => {
  if (newStartTime && newEndTime) {
    // 确保结束时间晚于开始时间
    if (newEndTime > newStartTime) {
      // 计算时长（分钟）
      const diffMs = newEndTime.getTime() - newStartTime.getTime()
      const diffMinutes = Math.round(diffMs / (1000 * 60))
      form.value.durationMinutes = diffMinutes
      
      // 同时更新热量
      updateCalories()
    }
  }
})

// 当运动类型或时长或强度变化时，计算热量消耗
watch([() => form.value.exerciseTypeId, () => form.value.durationMinutes, () => form.value.intensity], () => {
  updateCalories()
})

// 更新热量计算的函数
const updateCalories = () => {
  const exerciseType = exerciseTypes.value.find(type => type.id === form.value.exerciseTypeId)
  if (exerciseType && form.value.durationMinutes) {
    // 根据运动类型的卡路里/分钟系数、时长和强度系数计算总热量
    const caloriesPerMinute = exerciseType.caloriesPerMinute || 0
    const intensityMultiplier = getIntensityMultiplier(form.value.intensity)
    form.value.caloriesBurned = Number((caloriesPerMinute * form.value.durationMinutes * intensityMultiplier).toFixed(2))
  }
}

// 编辑记录
const handleEdit = (record) => {
  currentRecord.value = record
  form.value = {
    exerciseTypeId: record.exerciseType?.id,
    startTime: record.startTime ? new Date(record.startTime) : null,
    endTime: record.endTime ? new Date(record.endTime) : null,
    durationMinutes: record.durationMinutes,
    caloriesBurned: record.caloriesBurned,
    intensity: record.intensity || 'MEDIUM',
    location: record.location || '',
    notes: record.notes || ''
  }
  
  // 保存原始值
  originalValues.value = {
    durationMinutes: record.durationMinutes,
    caloriesBurned: record.caloriesBurned
  }
  
  dialogVisible.value = true
}

// 删除记录
const handleDelete = (record) => {
  ElMessageBox.confirm(
    '确定要删除这条运动记录吗？此操作不可恢复。',
    '删除运动记录',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUserExerciseRecord(selectedUserId.value, record.id)
      ElMessage.success('删除运动记录成功')
      // 刷新记录列表和统计数据
      fetchUserRecords(selectedUserId.value)
      fetchUserStats(selectedUserId.value)
    } catch (error) {
      console.error('删除运动记录失败:', error)
      ElMessage.error('删除运动记录失败')
    }
  }).catch(() => {})
}

// 保存原始的时长和热量值，用于恢复
const originalValues = ref({
  durationMinutes: 0,
  caloriesBurned: 0
})

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      // 日期格式化函数
      const formatDate = (date) => {
        if (!date) return null
        const pad = (num) => String(num).padStart(2, '0')
        const year = date.getFullYear()
        const month = pad(date.getMonth() + 1)
        const day = pad(date.getDate())
        const hours = pad(date.getHours())
        const minutes = pad(date.getMinutes())
        const seconds = pad(date.getSeconds())
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      // 构建提交的数据，使用表单计算后的时长和热量值
      const submitData = {
        exerciseType: {
          id: form.value.exerciseTypeId
        },
        startTime: formatDate(form.value.startTime),
        endTime: formatDate(form.value.endTime),
        durationMinutes: form.value.durationMinutes,
        caloriesBurned: form.value.caloriesBurned,
        intensity: form.value.intensity,
        location: form.value.location,
        notes: form.value.notes
      }
      
      await updateUserExerciseRecord(
        selectedUserId.value,
        currentRecord.value.id,
        submitData
      )
      
      ElMessage.success('更新运动记录成功')
      dialogVisible.value = false
      
      // 刷新记录列表和统计数据
      fetchUserRecords(selectedUserId.value)
      fetchUserStats(selectedUserId.value)
    } catch (error) {
      console.error('更新运动记录失败:', error)
      ElMessage.error(error.response?.data?.message || '更新运动记录失败')
    } finally {
      submitting.value = false
    }
  })
}

// 计算BMI分类
const getBmiCategory = (bmi) => {
  if (!bmi) return '未知'
  if (bmi < 18.5) return '偏瘦'
  if (bmi < 24) return '正常'
  if (bmi < 28) return '超重'
  if (bmi < 32) return '肥胖'
  return '严重肥胖'
}

// 获取BMI标签类型
const getBmiTagType = (bmi) => {
  if (!bmi) return 'info'
  if (bmi < 18.5) return 'warning' // 偏瘦
  if (bmi < 24) return 'success'   // 正常
  if (bmi < 28) return 'warning'   // 超重
  return 'danger'                  // 肥胖
}

// 获取目标类型显示名称
const getGoalTypeDisplayName = (type) => {
  const typeMap = {
    'WEIGHT_LOSS': '减重目标',
    'EXERCISE_FREQUENCY': '运动频率',
    'DISTANCE': '距离目标',
    'STRENGTH': '力量目标',
    'ENDURANCE': '耐力目标',
    'CUSTOM': '自定义'
  }
  return typeMap[type] || type
}

// 获取目标状态显示名称
const getGoalStatusDisplayName = (status) => {
  const statusMap = {
    'ACTIVE': '进行中',
    'COMPLETED': '已完成',
    'FAILED': '未达成',
    'ABANDONED': '已放弃'
  }
  return statusMap[status] || status
}

// 获取目标状态标签类型
const getGoalStatusType = (status) => {
  const typeMap = {
    'ACTIVE': 'primary',
    'COMPLETED': 'success',
    'FAILED': 'danger',
    'ABANDONED': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取进度状态
const getProgressStatus = (progress) => {
  if (progress === 100) return 'success'
  if (progress >= 80) return 'success'
  if (progress >= 50) return ''
  if (progress >= 20) return 'warning'
  return 'exception'
}

// 获取用户健康数据
const fetchUserHealthData = async (userId) => {
  if (!userId) return
  
  healthDataLoading.value = true
  try {
    healthData.value = await getUserHealthData(userId)
  } catch (error) {
    console.error('获取用户健康数据失败:', error)
    ElMessage.error('获取用户健康数据失败')
  } finally {
    healthDataLoading.value = false
  }
}

// 处理编辑健康数据
const handleEditHealthData = (data) => {
  currentHealthData.value = data
  healthDataForm.value = {
    recordDate: data.recordDate,
    height: data.height,
    weight: data.weight,
    bmi: data.bmi,
    restingHeartRate: data.restingHeartRate
  }
  
  healthDataDialogVisible.value = true
}

// 计算BMI值
const calculateBmi = () => {
  if (healthDataForm.value.height && healthDataForm.value.weight) {
    const heightInMeters = healthDataForm.value.height / 100.0
    healthDataForm.value.bmi = Number((healthDataForm.value.weight / (heightInMeters * heightInMeters)).toFixed(2))
  }
}

// 监听身高和体重变化，计算BMI
watch([() => healthDataForm.value.height, () => healthDataForm.value.weight], () => {
  calculateBmi()
})

// 提交健康数据表单
const submitHealthDataForm = async () => {
  if (!healthDataFormRef.value) return
  
  await healthDataFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    healthDataSubmitting.value = true
    
    try {
      // 构建提交的数据
      const submitData = {
        recordDate: healthDataForm.value.recordDate,
        height: healthDataForm.value.height,
        weight: healthDataForm.value.weight,
        bmi: healthDataForm.value.bmi,
        restingHeartRate: healthDataForm.value.restingHeartRate
      }
      
      await updateUserHealthData(
        selectedUserId.value,
        currentHealthData.value.id,
        submitData
      )
      
      ElMessage.success('更新健康数据成功')
      healthDataDialogVisible.value = false
      
      // 刷新健康数据列表
      fetchUserHealthData(selectedUserId.value)
    } catch (error) {
      console.error('更新健康数据失败:', error)
      ElMessage.error(error.response?.data?.message || '更新健康数据失败')
    } finally {
      healthDataSubmitting.value = false
    }
  })
}

// 删除健康数据
const handleDeleteHealthData = (data) => {
  ElMessageBox.confirm(
    '确定要删除这条健康数据记录吗？此操作不可恢复。',
    '删除健康数据',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUserHealthData(selectedUserId.value, data.id)
      ElMessage.success('删除健康数据成功')
      // 刷新健康数据列表
      fetchUserHealthData(selectedUserId.value)
    } catch (error) {
      console.error('删除健康数据失败:', error)
      ElMessage.error('删除健康数据失败')
    }
  }).catch(() => {})
}

// 处理目标状态筛选变化
const handleGoalStatusChange = () => {
  fetchUserFitnessGoalsByStatusFilter(selectedUserId.value, goalStatusFilter.value)
}

// 获取用户所有健身目标
const fetchUserFitnessGoals = async (userId) => {
  if (!userId) return
  
  goalsLoading.value = true
  try {
    // 重置筛选条件
    goalStatusFilter.value = 'ALL'
    fitnessGoals.value = await getUserFitnessGoals(userId)
  } catch (error) {
    console.error('获取用户健身目标失败:', error)
    ElMessage.error('获取用户健身目标失败')
  } finally {
    goalsLoading.value = false
  }
}

// 根据状态获取用户健身目标
const fetchUserFitnessGoalsByStatusFilter = async (userId, status) => {
  if (!userId) return
  
  goalsLoading.value = true
  try {
    if (status === 'ALL') {
      fitnessGoals.value = await getUserFitnessGoals(userId)
    } else {
      fitnessGoals.value = await getUserFitnessGoalsByStatus(userId, status)
    }
  } catch (error) {
    console.error('获取用户健身目标失败:', error)
    ElMessage.error('获取用户健身目标失败')
  } finally {
    goalsLoading.value = false
  }
}

// 处理编辑健身目标
const handleEditGoal = (goal) => {
  currentGoal.value = goal
  goalForm.value = {
    title: goal.title,
    description: goal.description || '',
    type: goal.type,
    targetValue: goal.targetValue || '',
    unit: goal.unit || '',
    startDate: goal.startDate,
    targetDate: goal.targetDate,
    progress: goal.progress || 0,
    status: goal.status
  }
  
  goalDialogVisible.value = true
}

// 提交健身目标表单
const submitGoalForm = async () => {
  if (!goalFormRef.value) return
  
  await goalFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    goalSubmitting.value = true
    
    try {
      // 构建提交的数据
      const submitData = {
        title: goalForm.value.title,
        description: goalForm.value.description,
        type: goalForm.value.type,
        targetValue: goalForm.value.targetValue,
        unit: goalForm.value.unit,
        startDate: goalForm.value.startDate,
        targetDate: goalForm.value.targetDate,
        progress: goalForm.value.progress,
        status: goalForm.value.status
      }
      
      await updateUserFitnessGoal(
        selectedUserId.value,
        currentGoal.value.id,
        submitData
      )
      
      ElMessage.success('更新健身目标成功')
      goalDialogVisible.value = false
      
      // 刷新健身目标列表
      if (goalStatusFilter.value === 'ALL' || goalStatusFilter.value === submitData.status) {
        fetchUserFitnessGoalsByStatusFilter(selectedUserId.value, goalStatusFilter.value)
      } else {
        goalStatusFilter.value = 'ALL'
        fetchUserFitnessGoals(selectedUserId.value)
      }
    } catch (error) {
      console.error('更新健身目标失败:', error)
      ElMessage.error(error.response?.data?.message || '更新健身目标失败')
    } finally {
      goalSubmitting.value = false
    }
  })
}

// 处理编辑目标进度
const handleEditGoalProgress = (goal) => {
  currentGoal.value = goal
  progressValue.value = goal.progress || 0
  progressDialogVisible.value = true
}

// 更新目标进度
const updateGoalProgress = async () => {
  progressSubmitting.value = true
  
  try {
    await updateUserGoalProgress(
      selectedUserId.value,
      currentGoal.value.id,
      progressValue.value
    )
    
    ElMessage.success('更新目标进度成功')
    progressDialogVisible.value = false
    
    // 刷新健身目标列表
    fetchUserFitnessGoalsByStatusFilter(selectedUserId.value, goalStatusFilter.value)
  } catch (error) {
    console.error('更新目标进度失败:', error)
    ElMessage.error(error.response?.data?.message || '更新目标进度失败')
  } finally {
    progressSubmitting.value = false
  }
}

// 删除健身目标
const handleDeleteGoal = (goal) => {
  ElMessageBox.confirm(
    '确定要删除这个健身目标吗？此操作不可恢复。',
    '删除健身目标',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteUserFitnessGoal(selectedUserId.value, goal.id)
      ElMessage.success('删除健身目标成功')
      // 刷新健身目标列表
      fetchUserFitnessGoalsByStatusFilter(selectedUserId.value, goalStatusFilter.value)
    } catch (error) {
      console.error('删除健身目标失败:', error)
      ElMessage.error('删除健身目标失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchUsers()
  fetchExerciseTypes()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.user-selector-card,
.stats-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-container {
  padding: 10px 0;
}

.stat-item {
  text-align: center;
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 13px;
}

.table-card, 
.records-card,
.filters-card {
  margin-bottom: 20px;
}

.progress-form {
  padding: 10px;
}

.progress-form h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.progress-form p {
  margin-bottom: 20px;
  color: #606266;
}

.current-progress {
  margin-bottom: 20px;
}

.current-progress span {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}
</style> 